package com.plian.system.service.pm.property;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.RedisUtils;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.pm.contributor.ContributorRecordDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundRecordDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationRecordDao;
import com.plian.system.dao.pm.property.PropertyBasicsDao;
import com.plian.system.dao.pm.property.PropertyDao;
import com.plian.system.dao.pm.property.PropertyRecordDao;
import com.plian.system.dao.pm.propertychange.PropertyChangeDao;
import com.plian.system.dao.pm.shareholding.ShareholdingRecordDao;
import com.plian.system.entity.qg.subsidiary.SubsidiaryMixedReform;
import com.plian.system.mapper.qg.subsidiary.SubsidiaryMixedReformMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.vo.pm.property.TreeSumVO;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PropertyRecordService {
    private static final Logger log = LoggerFactory.getLogger(PropertyRecordService.class);

    @Autowired
    PropertyRecordDao propertyRecordDao;
    @Autowired
    PropertyBasicsDao propertyBasicsDao;
    @Autowired
    BaseInfoDao baseInfoDao;
    @Autowired
    ContributorRecordDao contributorRecordDao;
    @Autowired
    ShareholdingRecordDao shareholdingRecordDao;
    @Autowired
    PartnerSituationRecordDao partnerSituationRecordDao;
    @Autowired
    PartnerOutboundRecordDao partnerOutboundRecordDao;
    @Autowired
    PropertyChangeDao propertyChangeDao;
    @Autowired
    PropertyDao propertyDao;
    @Autowired
    BaseInfoService baseInfoService;
    @Autowired
    private Environment environment;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private GzwProperties gzwProperties;

    @Autowired
    private FileService fileService;

    @Resource
    private SubsidiaryMixedReformMapper subsidiaryMixedReformMapper;

    public ListResult listPage(PageData pd){
//        pd.put("unStatus","4");
        Page page=new Page(false,pd);
        try {
            //得到当前单位的产权
            PageData propertyPd = new PageData();
            propertyPd.put("orgId", TokenUtil.getTokenOrgId());
            propertyPd.put("competentOrganization", TokenUtil.getCompetentOrganization());
            PageData p = propertyBasicsDao.findByOrgIdAndCom(propertyPd);
            List<PageData> l=new ArrayList<>();
            if(p!=null){
                PageData p1=propertyRecordDao.newFindByid(p.getString("id"));
                l.add(p1);
                List<PageData> list=propertyRecordDao.listPage(page);
                TreeUtli treeUtli=new TreeUtli();
                List<PageData> l1=treeUtli.getChlidList(p1.getString("initialId"),list,null,"parentId","initialId");
               if(l1!=null &&l1.size()>0){
                   l.addAll(l1);
               }
            }
            String keyWord=pd.getString("keyword");
            if(Tools.notEmpty(keyWord)){
                l=l.stream().filter(pageData ->
                        pageData.getString("orgName").contains(keyWord) ||
                                (Tools.notEmpty(pageData.getString("orgCode"))&&pageData.getString("orgCode").contains(keyWord))

                ).collect(Collectors.toList());
            }
            l=l.stream().filter(pageData -> !"4".equals(pageData.getString("status"))).collect(Collectors.toList());
            ListResult listResult=new ListResult(CommonCode.SUCCESS);
            int PageNumber=pd.getInteger("pageNumber");
            int PageSize=pd.getInteger("pageSize");
            int pageTotal = (PageNumber - 1) * PageSize;
            int pageTotal1 = PageNumber * PageSize;
            if (l.size() < pageTotal1) {
                listResult.setList(l.subList(pageTotal, l.size()));
            } else {
                listResult.setList(l.subList(pageTotal, pageTotal1));
            }
            listResult.setTotal(l.size());
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }
    public ObjResult findByid(PageData pd){
        try {
            PageData p1=propertyChangeDao.findbyid(pd.getString("id"));
            PageData p=propertyRecordDao.findbyid(p1.getString("proId"));

            String pro_id=p.getString("id");
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));
            p.put("stateFundedRelationName", stateFundedRelationName(p.getString("stateFundedRelation")));

            //出资人情况
            List<PageData> list_con= contributorRecordDao.find_parentId(pro_id);
            if(Tools.notEmpty(p.getString("nature"))){
                if("1".equals(p.getString("nature"))){
                    List<PageData> list_share= shareholdingRecordDao.find_parentId(pro_id);
                    p.put("list_share",list_share);
                }
                if("2".equals(p.getString("nature"))){
                    List<PageData> list_PartnerSituation = partnerSituationRecordDao.find_parentId(pro_id);
                    p.put("listPartnerSituation", list_PartnerSituation);
                    List<PageData> list_PartnerOutbound = partnerOutboundRecordDao.find_parentId(pro_id);

                    List<String> parentId1=new ArrayList<>();
                    parentId1.add("110");
                    PageData p_o1=new PageData();
                    p_o1.put("parentId",parentId1);
                    List<Tree> l=baseInfoDao.findTree(p_o1);
                    for (PageData pageData : list_PartnerOutbound) {
                        String industry=pageData.getString("industry");
                        if(Tools.notEmpty(industry)){
                            pageData.put("industryName", industryNames(industry,l));
                            pageData.put("industry", Arrays.asList(industry.split(",")));
                        }
                    }
                    p.put("listPartnerOutbound", list_PartnerOutbound);
                }
            }
            if(Tools.notEmpty(p.getString("majorIndustries"))){
                p.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
                p.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
            }else{
                p.put("majorIndustriesNames", new ArrayList<>());
                p.put("majorIndustries", new ArrayList<>());
            }
            p.put("list_con", list_con);

            for (int i = 1; i <=6; i++) {
                String v=p.getString("actualCapital"+i);
                if(Tools.isEmpty(v)|| "0".equals(v)){
                    p.put("actualCapital"+i,"0.00");
                }else{
                    BigDecimal b=new BigDecimal(v).setScale(2,BigDecimal.ROUND_HALF_UP);
                    p.put("actualCapital"+i,b.toPlainString());
                }
            }

            fileService.fileList(p);
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    private String netWorkingName(String netWorking){
        Map<String, String> netWorkingMap = baseInfoService.getChildMap(ValueSetConstant.NET_WORKING_TYPE);
        if (com.plian.Tools.StringUtil.isNotBlank(netWorking) && netWorkingMap.containsKey(netWorking)) {
            return netWorkingMap.get(netWorking);
        }
        return "";
    }

    private String stateFundedRelationName(String stateFundedRelation){
        Map<String, String> stateFundedRelationMap = baseInfoService.getChildMap(ValueSetConstant.STATE_FUNDED_RELATION);
        if (com.plian.Tools.StringUtil.isNotBlank(stateFundedRelation) && stateFundedRelationMap.containsKey(stateFundedRelation)) {
            return stateFundedRelationMap.get(stateFundedRelation);
        }
        return "";
    }

    public ObjResult chlidList(PageData pd){
        try {
            //得到当前单位的产权
            PageData propertyPd = new PageData();
            propertyPd.put("orgId", TokenUtil.getTokenOrgId());
            propertyPd.put("competentOrganization", TokenUtil.getCompetentOrganization());
            PageData org = propertyBasicsDao.findByOrgIdAndCom(propertyPd);
            List<PageData> arrayList=new ArrayList<>();
            if(org!=null){
                PageData p1=propertyRecordDao.newFindByid(org.getString("id"));
                if(Tools.notEmpty(pd.getString("id"))&&
                        p1.getString("id").equals(pd.getString("id"))){
                    PageData parent=propertyBasicsDao.findbyid(p1.getString("parentId"));
                    PageData parent1=propertyRecordDao.newFindByid(parent.getString("id"));
                    arrayList.add(parent1);
                }else{
                        arrayList.add(p1);
                        Page page=new Page(false,pd);
                        List<PageData> list=propertyRecordDao.listPage(page);
                        TreeUtli treeUtli=new TreeUtli();
                        List<PageData> l1=treeUtli.getChlidList(p1.getString("initialId"),list,null,"parentId","initialId");
                        if(l1!=null &&l1.size()>0){
                            arrayList.addAll(l1);
                        }
                }
            }
            PageData p=new PageData();
            p.put("list",arrayList);
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 行业转换
     * @return
     */
    private List<String> industryNames(String codes) throws Exception {
        List<String> l= Arrays.asList(codes.split(","));
        List<PageData> baseInfo= baseInfoDao.findbycodes(l);
        List l1=new ArrayList();
        for (String code : l) {
            String s1="";
            for (PageData pageData : baseInfo) {
                if(pageData.getString("code").equals(code)){
                    s1=pageData.getString("name");
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }


    public ObjResult newFindByid(PageData pd){
        try {
            PageData p=propertyRecordDao.findbyid(pd.getString("id"));
            PageData p1=propertyRecordDao.newFindByid(p.getString("initialId"));
            String pro_id=p1.getString("id");
            //出资人情况
            List<PageData> list_con= contributorRecordDao.find_parentId(pro_id);
            if(Tools.notEmpty(p1.getString("nature"))){
                if("1".equals(p1.getString("nature"))){
                    List<PageData> list_share= shareholdingRecordDao.find_parentId(pro_id);
                    p1.put("list_share",list_share);
                }
                if("2".equals(p1.getString("nature"))){
                    List<PageData> list_PartnerSituation = partnerSituationRecordDao.find_parentId(pro_id);
                    p1.put("listPartnerSituation", list_PartnerSituation);
                    List<PageData> list_PartnerOutbound = partnerOutboundRecordDao.find_parentId(pro_id);

                    List<String> parentId1=new ArrayList<>();
                    parentId1.add("110");
                    PageData p_o1=new PageData();
                    p_o1.put("parentId",parentId1);
                    List<Tree> l=baseInfoDao.findTree(p_o1);
                    for (PageData pageData : list_PartnerOutbound) {
                        String industry=pageData.getString("industry");
                        if(Tools.notEmpty(industry)){
                            pageData.put("industryName", industryNames(industry,l));
                            pageData.put("industry", Arrays.asList(industry.split(",")));
                        }
                    }
                    p1.put("listPartnerOutbound", list_PartnerOutbound);
                }
            }
            if(Tools.notEmpty(p1.getString("majorIndustries"))){
                p1.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
                p1.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
            }else{
                p1.put("majorIndustriesNames", new ArrayList<>());
                p1.put("majorIndustries", new ArrayList<>());
            }

            p1.put("stateFundedRelationName", stateFundedRelationName(p1.getString("stateFundedRelation")));
            p1.put("list_con", list_con);
            fileService.fileList(p1);
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p1);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ObjResult isRepeat(PageData pd){
        ObjResult objResult;
        objResult=new ObjResult(CommonCode.SUCCESS);
        PageData p=new PageData();
        p.put("isRepeat",isRepeat1(pd));
        objResult.setPageData(p);
        return objResult;
    }


    /**
     * 行业转换
     * @return
     */
    private List<String> industryNames(String codes,List<Tree> list) throws Exception {
        List<String> l= Arrays.asList(codes.split(","));
        List l1=new ArrayList();
        for (String code : l) {
            String s1="";
            for (Tree pageData : list) {
                if(pageData.getCode().equals(code)){
                    s1=pageData.getName();
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }


    /**
     * 校验是否重复
     * @param pd
     * @return
     */
    private String isRepeat1(PageData pd) {
        try {
            boolean a=true;
            boolean nameFlag=true;//企业名称重复标记
            boolean orgCodeFlag=true;//社会信用代码重复标记
            if(Tools.notEmpty(pd.getString("id"))){
                PageData pageData=propertyChangeDao.findbyid(pd.getString("id"));
                //PageData p=propertyBasicsDao.findbyid(pageData.getString("initialId"));
                if(pageData.getString("orgName").equals(pd.getString("orgName"))){
                    nameFlag=false;
                }
                if(pageData.getString("orgCode").equals(pd.getString("orgCode"))){
                    orgCodeFlag=false;
                }
                if(pd.getString("pId").equals(pageData.getString("id"))) {
                    return "1";
                }
            }else{
                a=true;
            }
            if(a){
                String proId=pd.getString("proId");
                PageData p=propertyRecordDao.findbyid(proId);
                if(p.get("orgName").toString().equals(pd.getString("orgName"))){
                    nameFlag=false;
                }
                if(pd.get("orgCode").toString().equals(p.getString("orgCode"))){
                    orgCodeFlag=false;
                }
            }

            if(a){
                pd.put("competentOrganization", TokenUtil.getCompetentOrganization());

                PageData pd1=new PageData();
                pd1.putAll(pd);
                PageData pd2=new PageData();
                pd2.putAll(pd);
                pd1.remove("orgCode");
                pd1.put("orgName",pd.getString("orgName"));
                pd2.remove("orgName");
                pd2.put("orgCode",pd.getString("orgCode"));
                if(nameFlag){
                    List<PageData> l2=propertyChangeDao.listByOrgCodeOrName(pd1);
                    if(l2!=null&&l2.size()>0){
                        return "2";
                    }
                    List<PageData> l = propertyBasicsDao.list(pd1);
                    if(l!=null &&l.size()>0){
                        return "2";
                    }
                    List<PageData> l4 =  propertyDao.noApprovalList(pd1);
                    if(l4!=null && l4.size()>0){
                        return "2";
                    }
                }
                if(orgCodeFlag){
                    List<PageData> l1 = propertyBasicsDao.list(pd2);
                    if(l1!=null &&l1.size()>0){
                        return "3";
                    }
                    List<PageData> l3=propertyChangeDao.listByOrgCodeOrName(pd2);
                    if(l3!=null&&l3.size()>0){
                        return "3";//信用代码重复
                    }
                    List<PageData> l5 =  propertyDao.noApprovalList(pd2);
                    if(l5!=null && l5.size()>0){
                        return "3";
                    }
                }
            }else{
                return "0";
            }
            return "0";
        }
        catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw  new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    public PageData treeDate(PageData pd) throws Exception {
        String treeType = pd.getString("treeType");
        if (Tools.isEmpty(pd.getString("date"))) {
            pd.put("date", Tools.date2Str(new Date(), "yyyy-MM-dd"));
        }
        pd.put("date", pd.getString("date") + " 23:59:59");
        //某个时间点的产权信息
        List<PageData> list=propertyRecordDao.treeList(pd);
        //市本级
        if (StringUtil.isNotBlank(treeType) && "2".equals(treeType)){
            list = list.stream().filter(m -> gzwProperties.getId().equals(m.getString("competentOrganization"))).collect(Collectors.toList());
        }
        PageData  pro=new PageData();
        List<String> recordIds = new ArrayList<>();
        for (PageData pageData : list) {
            pageData.put("label",pageData.getString("orgName"));
            recordIds.add(pageData.getString("recordId"));
            if(pd.getString("id").equals(pageData.getString("id"))){
                pro.putAll(pageData);
            }
        }
        Map<String, List<PageData>> contributorRecordMap = new HashMap<>();
        Map<String, List<PageData>> partnerSituationRecordMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(recordIds)){
            List<PageData> contributorRecords = contributorRecordDao.findByParentIds(recordIds);

            for (PageData contributorRecord : contributorRecords) {
                List<PageData> childList = new ArrayList<>();
                if (!contributorRecordMap.containsKey(contributorRecord.getString("propertyId"))){
                    contributorRecordMap.put(contributorRecord.getString("propertyId"), childList);
                }
                String equityRatio = contributorRecord.getString("equityRatio");
                if (StringUtil.isNotBlank(equityRatio)){
                    contributorRecord.put("equityRatio",new BigDecimal(equityRatio).setScale(4, RoundingMode.HALF_UP).toPlainString());
                }
                childList = contributorRecordMap.get(contributorRecord.getString("propertyId"));
                childList.add(contributorRecord);
            }
            List<PageData> partnerSituationRecords = partnerSituationRecordDao.findByParentIds(recordIds);
            if (CollectionUtil.isNotEmpty(partnerSituationRecords)){
                partnerSituationRecordMap = partnerSituationRecords.stream().collect(Collectors.groupingBy(partnerSituationRecord ->
                        partnerSituationRecord.getString("propertyId")));
            }


            for (PageData property : list) {
                property.put("contributors", "");
                if (contributorRecordMap.containsKey(property.getString("recordId"))){
                    List<PageData> childList = contributorRecordMap.get(property.getString("recordId"));
                    property.put("contributors", getContributorsStr(childList));
                }
                if ("2".equals(property.getString("nature"))){
                    if (partnerSituationRecordMap.containsKey(property.getString("recordId"))){
                        List<PageData> childList = partnerSituationRecordMap.get(property.getString("recordId"));
                        property.put("contributors", getPartnerSituationStr(childList));
                    }
                }

            }
        }

        List<PageData> l1=new ArrayList<>();
        if(pro!=null && pro.size()>0){
            TreeUtli treeUtli=new TreeUtli();
            l1= treeUtli.getChlid(pro.getString("id"),list);
            pro.put("children",l1);
            pro.put("contributors", "");
            if (contributorRecordMap.containsKey(pro.getString("recordId"))){
                List<PageData> childList = contributorRecordMap.get(pro.getString("recordId"));
                pro.put("contributors", getContributorsStr(childList));
            }
            if ("2".equals(pro.getString("nature"))){
                if (partnerSituationRecordMap.containsKey(pro.getString("recordId"))){
                    List<PageData> childList = partnerSituationRecordMap.get(pro.getString("recordId"));
                    pro.put("contributors", getPartnerSituationStr(childList));
                }
            }
        }
        PageData result=new PageData();
        List<PageData> l2=new ArrayList<>();
//        l2.add(pro);
        //混改
        if (StringUtil.isNotBlank(treeType) && "3".equals(treeType)){
            List<SubsidiaryMixedReform> mixedReforms = subsidiaryMixedReformMapper.selectList(new LambdaQueryWrapper<SubsidiaryMixedReform>()
                    .eq(SubsidiaryMixedReform::getStatus, 3).eq(SubsidiaryMixedReform::getIsLatest, 2));
            if (CollectionUtil.isNotEmpty(mixedReforms)) {
                Set<String> mixedIds = mixedReforms.stream().map(SubsidiaryMixedReform::getMixedEnterpriseId).collect(Collectors.toSet());
                setIsMixed(pro,mixedIds);
                if (pro.containsKey("children")){
                    removeNotMixed((List<PageData>) pro.get("children"));
                }

            }
        }
        l2.add(pro);
        result.put("tree",l2);
        return result;

    }


    /**
     * @Author: Take-off
     * @Description: //TODO 减去非混改产权
     * @Date: 3:10 PM 2023/2/23
     * @Param: [children]
     * @return: void
     **/
    private void removeNotMixed(List<PageData> children){
        if (CollectionUtil.isNotEmpty(children)){
            for (int i = children.size() -1; i>=0 ;i--){
                PageData pageData = children.get(i);
                if (pageData.containsKey("children")){
                    List<PageData> child = (List<PageData>) pageData.get("children");
                    if (CollectionUtil.isNotEmpty(child)){
                        removeNotMixed(child);
                        if (CollectionUtil.isEmpty(child)){
                            pageData.remove("children");
                            if (pageData.getInteger("isMix") == 0){
                                children.remove(pageData);
                            }
                        }
                    }else {
                        pageData.remove("children");
                        if (pageData.getInteger("isMix") == 0){
                            children.remove(pageData);
                        }
                    }
                }else {
                    if (pageData.getInteger("isMix") == 0){
                        children.remove(pageData);
                    }
                }
            }
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 打上混改标记
     * @Date: 3:09 PM 2023/2/23
     * @Param: [pageData, mixIds]
     * @return: void
     **/
    private void setIsMixed(PageData pageData,Set<String> mixIds){
        if (pageData.containsKey("children")){
            List<PageData> children = (List<PageData>) pageData.get("children");
            for (PageData pd:children){
                setIsMixed(pd,mixIds);
            }
        }
        //匹配混改Id
        if (mixIds.contains(pageData.getString("id"))){
            pageData.put("isMix",1);
        }else {
            pageData.put("isMix",0);
        }

    }

    public String treeExport(PageData pd){
        try{
            String key = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().replace("-", "");
            String fileName = key + ".xlsx";
            String exportPath = environment.getProperty("excel.path");

            /**
             * 导出路径不存在则创建
             */
            File file = new File(exportPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            List<PageData> treeList = (List<PageData>)treeDate(pd).get("tree");
            String excelName = treeList.get(0).getString("orgName") + "下的产权树";
            List<Tree> trees = pageDataToTree(treeList, 1);

            List<TreeSumVO> treeSumVOS = treeTotal(pd).getList();

            PropertyTreeExportHelper.create(trees, treeSumVOS, exportPath, fileName);
            redisUtils.set(key, excelName, 10 * 60);
            return key;
        }catch (Exception e){
            log.error(e+"");
           throw new MyRuntimeException(new ObjResult("产权树导出异常！"));
        }

    }

    private List<Tree> pageDataToTree(List<PageData> list, int level){
        List<Tree> treeList = new ArrayList();
        if (CollectionUtil.isNotEmpty(list)){
            for (PageData pd : list){
                Tree tree = new Tree();
                tree.setLevel(level);
                tree.setId(pd.getString("id"));
                String contributors = pd.getString("contributors");

                String name = "";
                String regCapital = pd.getString("regCapital");
                if (StringUtil.isNotBlank(regCapital)){
                    name = "(注册资本" + regCapital + "万元";
                }
                if (StringUtil.isNotBlank(contributors)){
                    if (StringUtil.isNotBlank(name)){
                        name = name + ";股比：" + contributors + ")";
                    }else {
                        name = "(股比：" + contributors + ")";
                    }
                }
                name =  pd.getString("orgName") + name;
                tree.setName(name);
                String orgCategory = pd.getString("orgCategory");
                if (StringUtil.isNotBlank(orgCategory)){
                    //全资企业
                    if("045001".equals(orgCategory)){
                        tree.setColor(IndexedColors.CORAL.getIndex());
                    }
                    // 国有绝对控股企业
                    if("045002".equals(orgCategory)|| "045003".equals(orgCategory)){
                        tree.setColor(IndexedColors.LIGHT_GREEN.getIndex());
                    }
                    //国有参股企业
                    if("045004".equals(orgCategory)){
                        tree.setColor(IndexedColors.TAN.getIndex());
                    }
                }
                treeList.add(tree);

                if (pd.containsKey("children") && CollectionUtil.isNotEmpty((List)pd.get("children"))){
                    tree.setChildren(pageDataToTree((List<PageData>)pd.get("children"), level + 1));
                }
            }
        }
        return treeList;
    }

    /**
     * 股权占比
     * @param contributors
     * @return
     */
    private String getContributorsStr(List<PageData> contributors){
        if (CollectionUtil.isNotEmpty(contributors)){
            StringBuffer stringBuffer = new StringBuffer();
            for (PageData child : contributors){
                if (stringBuffer.length() != 0){
                    stringBuffer.append(",");
                }
                stringBuffer.append(child.getString("contributor")).append(":").append(child.getString("equityRatio")).append("%");
            }
            return stringBuffer.toString();
        }
        return "";
    }

    private String getPartnerSituationStr(List<PageData> contributors){
        if (CollectionUtil.isNotEmpty(contributors)){
            StringBuffer stringBuffer = new StringBuffer();
            for (PageData child : contributors){
                if (stringBuffer.length() != 0){
                    stringBuffer.append(",");
                }
                stringBuffer.append(child.getString("name")).append(":").append(child.getString("subscribedProportion")).append("%");
            }
            return stringBuffer.toString();
        }
        return "";
    }

    public ListResult treeList(PageData pd){
        //某个时间点的产权信息
        try {
            PageData propertyPd = new PageData();
            propertyPd.put("orgId", TokenUtil.getTokenOrgId());
            propertyPd.put("competentOrganization", TokenUtil.getCompetentOrganization());
            PageData org = propertyBasicsDao.findByOrgIdAndCom(propertyPd);
            List<PageData> arrayList=new ArrayList<>();
            if(org!=null) {
                PageData p1 = propertyRecordDao.newFindByid(org.getString("id"));
                p1.put("id", p1.getString("initialId"));
                List<PageData> list=propertyRecordDao.getOneUnit(pd);
                TreeUtli treeUtli = new TreeUtli();
                List<PageData> l1 = treeUtli.getChlidList(p1.getString("initialId"), list, null);
                arrayList.add(p1);
                if (CollectionUtil.isNotEmpty(l1)){
                    arrayList.addAll(l1);
                }
            }

            ListResult listResult=new ListResult(CommonCode.SUCCESS);
            listResult.setList(arrayList);
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw  new MyRuntimeException();
        }
    }

    public ObjResult tree(PageData pd){
        ObjResult objResult;
        if(Tools.isEmpty(pd.getString("id"))){
            objResult=new ObjResult(CommonCode.ERRORPARAMETER);
            objResult.setMessage("请选择单位!!!");
            return  objResult;
        }
        if(Tools.isEmpty(pd.getString("date"))){
            objResult=new ObjResult(CommonCode.ERRORPARAMETER);
            objResult.setMessage("请选择日期!!!");
            return  objResult;
        }
        try {
            objResult=new ObjResult(CommonCode.SUCCESS);
            PageData p=treeDate(pd);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
           throw  new MyRuntimeException();
        }
    }


    public ListResult<TreeSumVO> treeTotal(PageData pd){
        //某个时间点的产权信息
        try {
            String treeType = pd.getString("treeType");

            String date=pd.getString("date")+" 23:59:59";
            pd.put("date",date);
            List<PageData>  l = propertyRecordDao.treeList(pd);
            //市本级
            if (StringUtil.isNotBlank(treeType) && "2".equals(treeType)){
                l = l.stream().filter(m -> gzwProperties.getId().equals(m.getString("competentOrganization"))).collect(Collectors.toList());
            }
            TreeUtli treeUtli=new TreeUtli();
            List<PageData> list = new ArrayList<>();
            list= treeUtli.getChlidList(pd.getString("id"), l, null);
            list.add(  l.stream().filter(propertyRecord -> propertyRecord.getString("id").equals(pd.getString("id"))).collect(Collectors.toList()).get(0));

            Map<String, String> rankMap = baseInfoService.getChildMap(ValueSetConstant.ENTERPRISE_RANK);
            Map<String, TreeSumVO> treeSumVOMap = new HashMap<>();
            TreeSumVO end = TreeSumVO.builder().countName("合计").whollyCount(0).holdingCount(0)
                    .participationCount(0).companyCount(0)
                    .build();
            if (StringUtil.isNotBlank(treeType) && "3".equals(treeType)){
                List<SubsidiaryMixedReform> mixedReforms = subsidiaryMixedReformMapper.selectList(new LambdaQueryWrapper<SubsidiaryMixedReform>()
                        .eq(SubsidiaryMixedReform::getStatus, 3).eq(SubsidiaryMixedReform::getIsLatest, 2));
                Set<String> mixedIds = mixedReforms.stream().map(SubsidiaryMixedReform::getMixedEnterpriseId).collect(Collectors.toSet());
                PageData pro = new PageData();
                pro.put("id",1);
                pro.put("children",list);
                setIsMixed(pro,mixedIds);
                if (pro.containsKey("children")){
                    removeNotMixed((List<PageData>) pro.get("children"));
                }
                List<PageData> list1 = (List<PageData>) pro.get("children");
                System.out.println();
            }


            for (PageData pageData : list) {
                pageData.put("label",pageData.getString("orgName"));
                //企业类别
                String orgCategory=pageData.getString("orgCategory");
                //企业级次
                String orgGradation=pageData.getString("orgGradation");
                if(Tools.notEmpty(orgGradation) && Tools.notEmpty(orgCategory)){
                    TreeSumVO treeSumVO;

                    //5级及以下特殊处理
                    if (Integer.valueOf(orgGradation) > 1004 && !"001099".equals(orgGradation)){
                        orgGradation = "other";
                    }
                    if (treeSumVOMap.containsKey(orgGradation)){
                        treeSumVO = treeSumVOMap.get(orgGradation);
                    }else {
                        treeSumVO = TreeSumVO.builder().whollyCount(0).holdingCount(0)
                                .participationCount(0).companyCount(0).orgGradation(orgGradation)
                                .build();
                        String countName = rankMap.get(orgGradation) + "子公司";
                        if ("001001".equals(orgGradation)){
                            countName = rankMap.get(orgGradation) + "企业";
                        }
                        if ("other".equals(orgGradation)){
                            countName = "5级及以下";
                        }
                        treeSumVO.setCountName(countName);
                        treeSumVOMap.put(orgGradation, treeSumVO);
                    }
                    //全资企业
                    if("045001".equals(orgCategory)){
                        treeSumVO.setWhollyCount(treeSumVO.getWhollyCount() + 1);
                        end.setWhollyCount(end.getWhollyCount() + 1);
                    }
                    // 国有绝对控股企业
                    if("045002".equals(orgCategory)|| "045003".equals(orgCategory)){
                        treeSumVO.setHoldingCount(treeSumVO.getHoldingCount() + 1);
                        end.setHoldingCount(end.getHoldingCount() + 1);
                    }
                    //国有参股企业
                    if("045004".equals(orgCategory)){
                        treeSumVO.setParticipationCount(treeSumVO.getParticipationCount() + 1);
                        end.setParticipationCount(end.getParticipationCount() + 1);
                    }
                    treeSumVO.setCompanyCount(treeSumVO.getCompanyCount()  + 1);
                    end.setCompanyCount(end.getCompanyCount()  + 1);
                }
            }

            List<TreeSumVO> results;
            ListResult<TreeSumVO> listResult = new ListResult<>(CommonCode.SUCCESS);
            if (CollectionUtil.isNotEmpty(treeSumVOMap)){
                results = new ArrayList<>(treeSumVOMap.values());
                results = results.stream().sorted(Comparator.comparing(TreeSumVO::getOrgGradation))
                    .collect(Collectors.toList());
                results.add(end);
                listResult.setList(results);
                listResult.setTotal(CollectionUtil.isNotEmpty(results) ? results.size() : 0);
            }

            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }


    }


    public ObjResult listAll(){
        try {
            PageData p=new PageData();
            p.put("list", propertyRecordDao.allList());
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
            log.error("获取产权记录所有列表失败" + e);
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

}
